package com.sakura.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sakura.common.R;
import com.sakura.pojo.User;
import com.sakura.serivce.UserService;
import com.sakura.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User phone, HttpSession session){
        log.info(phone.getPhone());
        // 调用工具类发送短信
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        log.info(code.toString());
        //存入短信到session
        // session.setAttribute("code", code.toString());

        //存入短信到Redis
        redisTemplate.opsForValue().set("code_"+phone.getPhone(),code.toString());
        return R.success("发送短信成功");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String, String> map, HttpSession session) {
        log.info(map.toString());
        //获取手机号
        String phone = map.get("phone");
        //获取验证码
        String code1 = map.get("code");
        //从Session中获取保存的验证码
        // String code2 = (String) session.getAttribute("code");
        // 获取Redis验证码
        String code2 = (String) redisTemplate.opsForValue().get("code_" + phone);

        //进行验证码的比对（页面提交的验证码和Session中保存的验证码比对）
        if (!StringUtils.equals(code1, code2)) {
            return R.error("验证码错误");
        }

        //判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        User user = userService.getOne(queryWrapper);
        if (user == null) {
            //新用户注册
            user = new User();
            user.setStatus(1);
            user.setPhone(phone);
            userService.save(user);
        }
        //将用户存入session中
        session.setAttribute("frontUserInfo", user.getId());
        // 销毁Redis手机验证码记录
        redisTemplate.delete("code_"+phone);
        return R.success(user);
    }
}
